#include <iostream>
#include <sstream>

#include "argvparser.h"
#include "Testing.h"

int main(int argc, char *argv[])
{


    CommandLineProcessing::ArgvParser cmd;

    Testing test;

    cmd.setIntroductoryDescription("Welcome to the testing environment for the ImageLib project.\n");

    std::cout << cmd.getIntroDescr() << "\n";
    std::cout << "> ";

    cmd.addErrorCode(0, "Success");
    cmd.addErrorCode(1, "Error");

    cmd.setHelpOption("h", "help", "Print this help page");

    cmd.defineOption("exit", "End program.",CommandLineProcessing::ArgvParser::NoOptionAttribute);
    cmd.defineOptionAlternative("exit", "quit");

    std::string buffer;
//    QString command ("");

    while (std::getline(std::cin, buffer)) // Where do I enter text within the console app??
    {
//        std::cout << buffer << "\n";

        int countArguments = 0; // ~argc
        std::istringstream iss (buffer);

        while(iss) {
            std::string tmp;
            iss >> tmp;
//            std::cout << "Inside loop " <<  bufferChar[countArguments] << "\n";
            countArguments++;
        }

        countArguments--;

        std::cout << countArguments << "\n";

        std::istringstream iss2 (buffer);

        //char* bufferChar = new char[500];

        char** ptrChar; // ~ argv

//        for (int i=0; i<countArguments; i++) {
//            *(bufferChar+i) = new char[30];
//        }
        int argvLength = 0;
        int cStringLength = 0;

        int i=0;
        while(iss2) {
            std::string tmp;
            getline(iss2, tmp, ' ');
            std::cout << tmp << "\n";
            cStringLength = strlen(tmp);
            char* currentBuf = new char[cStringLength];
            strncpy(currentBuf, const_cast<char*>(tmp.c_str()), cStringLength);
            std::cout << "Inside loop " << currentBuf << "\n";
            i++;
            argvLength += cStringLength;
        }

        std::cout << "Outside loop.\n";

        for(int i=0; i<countArguments; i++) {
//            for(int j=0; j<50; j++) {
                std::cout << bufferChar+(i*50);
//            }
            std::cout << "\n";
        }

        int result = cmd.parse(countArguments, ptrChar);

        if (result != CommandLineProcessing::ArgvParser::NoParserError)
        {
            std::cout << cmd.parseErrorDescription(result);
            exit(1);
        }

        if(cmd.foundOption("exit")) {
            test.endProgram();
        }
        else {
            std::cout << "No such option. Please try again.\n";
        }

        std::cout << "> ";

    }
}
